package com.runfast.waimai.web.controller.base;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * ${DESCRIPTION}
 *
 * @author chenzheng
 * @create 2018-05-05 15:26
 **/
@RequestMapping("/server/user")
@RestController("userController")
public class UserController {
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BaseUserRoleService baseUserRoleService;
    @Autowired
    private WaiMaiRunfastAgentaccountsService waiMaiRunfastAgentaccountsService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private RunfastBusinessService runfastBusinessService;
    @Autowired
    private RunfastBusinessAccountsService runfastBusinessAccountsService;
    /**
     * 所有用户列表---后期加入当前登录用户
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable,String realname,String mobile,Integer rid,String city,Integer agentId){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        Map<Object,Object> map1=new HashMap<Object, Object>();
        if(StringUtils.isNotBlank(realname)){
            map1.put("realname",realname);
        }
        if(StringUtils.isNotBlank(mobile)){
            map1.put("mobile",mobile);
        }
        if(rid!=null){
            map1.put("rid",rid);
        }
        Map<Object,Object> map=new HashMap<Object, Object>();
        Integer total=null;
        List<BaseUser> list=new ArrayList<BaseUser>();
        List<WaiMaiRunfastAgentaccounts> agentaccountsList=new ArrayList<WaiMaiRunfastAgentaccounts>();
        map1.put("pageable",pageable);
        if(admin!=null && admin.getType()==1){
            if(agentId!=null){
                map1.put("agentId",agentId);
                agentaccountsList=waiMaiRunfastAgentaccountsService.selectByMapWithPageable(map1);
                total=waiMaiRunfastAgentaccountsService.countByMap(map1);
                map.put("list",agentaccountsList);
                map.put("total",total);
            }else{
                //后台登录
                if(agentId==null){
                    map1.put("isNull",1);
                }
                list=baseUserService.selectUsersByExampleWithPageable(map1);
                total=baseUserService.countUsersByExample(map1);
                map.put("list",list);
                map.put("total",total);
            }
        } else if(admin!=null && admin.getType()==2 && agentaccounts!=null){
            if(agentId!=null){
                if(!agentId.equals(agentaccounts.getAgentid())){
                    return Result.fail(null,"只能查看自己的信息！");
                }
            }
            //代理商登录
            WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentaccounts.getAgentid());
            if(agentbusiness!=null){
                map1.put("agentId",agentbusiness.getId());
                agentaccountsList=waiMaiRunfastAgentaccountsService.selectByMapWithPageable(map1);
                total=waiMaiRunfastAgentaccountsService.countByMap(map1);
                map.put("list",agentaccountsList);
                map.put("total",total);
            }else{return Result.fail(null,"找不到对应的代理商！");}
        }else{return Result.fail(null,"未登录，重新登录！");}
        return Result.ok(null,map);
    }

    /**
     * 获取登录的用户信息---后期加入当前登录用户信息
     */
    @GetMapping("/info1")
    public Result info1(){
        BaseUser user=null;//当前登录用户
        return Result.ok(null,user);
    }

    /**
     * 修改登录用户密码
     */
    /*@PostMapping("/password")
    public Result password(@RequestBody PasswordForm form){
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if(!flag){
            return Result.fail(null,"原密码不正确");
        }

        return Result.ok(null);
    }*/

    /**
     * 用户信息
     */
    @GetMapping("/info")
    //@RequiresPermissions("server:user:info")
    public Result info(Integer id){
        BaseUser user = baseUserService.selectByPrimaryKey(id);

        //获取用户所属的角色列表
        List<Integer> roleIdList = baseUserRoleService.queryRoleIdList(id);
        //user.setRoleIdList(roleIdList);

        return Result.ok(null,user);
    }

    /**
     * 保存用户
     */
    @PostMapping("/save")
    public Result save(@RequestBody BaseUser user){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        if(user!=null && StringUtils.isNotBlank(user.getRealname())&&  StringUtils.isNotBlank(user.getMobile()) && user.getRid()!=null){
            if(admin!=null && admin.getType()==1){
                if(user.getAgentId()!=null){
                    WaiMaiRunfastAgentaccountsExample example=new WaiMaiRunfastAgentaccountsExample();
                    example.createCriteria().andAccountsEqualTo(user.getMobile());
                    Integer in=waiMaiRunfastAgentaccountsService.countByExample(example);
                    if(in>0){
                        return Result.fail(null,"该号码已经注册过了！");
                    }
                    WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(user.getAgentId());
                    if(agentbusiness!=null){
                        WaiMaiRunfastAgentaccounts newAgentaccounts=new WaiMaiRunfastAgentaccounts();
                        newAgentaccounts.setAgentid(agentbusiness.getId());
                        newAgentaccounts.setAgentname(agentbusiness.getName());
                        if(user.getRid()>0){
                            newAgentaccounts.setByroles(user.getRid().toString());
                        }else{return Result.fail(null,"保存人员角色不能为空！");}
                        newAgentaccounts.setAccounts(user.getMobile());
                        newAgentaccounts.setName(user.getRealname());
                        newAgentaccounts.setPassword(DigestUtils.md5Hex("123456"));
                        newAgentaccounts.setMobile(user.getMobile());
                        newAgentaccounts.setCreatetime(new Date());
                        newAgentaccounts.setTid(agentbusiness.getTid());
                        newAgentaccounts.setPid(agentbusiness.getPid());
                        newAgentaccounts.setCid(agentbusiness.getCid());
                        newAgentaccounts.setCityname(agentbusiness.getCityname());
                        newAgentaccounts.setProvince(agentbusiness.getProvince());
                        newAgentaccounts.setCountyname(agentbusiness.getCountyname());
                        waiMaiRunfastAgentaccountsService.insertSelective(newAgentaccounts);
                    }else{return Result.fail(null,"找不到对应的代理商！");}
                }else{
                    BaseUserExample example=new BaseUserExample();
                    example.createCriteria().andUsernameEqualTo(user.getMobile());
                    Integer in=baseUserService.countByExample(example);
                    if(in>0){
                        return Result.fail(null,"该号码已经注册过了！");
                    }
                    if(admin.getOrgid()!=null){
                        user.setOrgid(admin.getOrgid());
                    }
                    if(user.getMobile()!=null){
                        user.setUsername(user.getMobile());
                    }
                    user.setPassword(DigestUtils.md5Hex("123456"));//默认密码
                    user.setCreatetime(new Date());
                    user.setState(0);
                    baseUserService.insertSelective(user);
                    if(user.getRid()>0){
                        BaseUserRole userRole=new BaseUserRole();
                        userRole.setRid(user.getRid());
                        userRole.setUserid(user.getId());
                        baseUserRoleService.insertSelective(userRole);
                    }
                }
            }else if(admin!=null && admin.getType()==2 && agentaccounts!=null){
                WaiMaiRunfastAgentaccountsExample example=new WaiMaiRunfastAgentaccountsExample();
                example.createCriteria().andAccountsEqualTo(user.getMobile());
                Integer in=waiMaiRunfastAgentaccountsService.countByExample(example);
                if(in>0){
                    return Result.fail(null,"该号码已经注册过了！");
                }
                WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentaccounts.getAgentid());
                if(agentbusiness!=null){
                    WaiMaiRunfastAgentaccounts newAgentaccounts=new WaiMaiRunfastAgentaccounts();
                    newAgentaccounts.setAgentid(agentaccounts.getAgentid());
                    newAgentaccounts.setAgentname(agentaccounts.getAgentname());
                    if(user.getRid()>0){
                        newAgentaccounts.setByroles(user.getRid().toString());
                    }else{return Result.fail(null,"保存人员角色不能为空！");}
                    newAgentaccounts.setAccounts(user.getMobile());
                    newAgentaccounts.setName(user.getRealname());
                    newAgentaccounts.setPassword(DigestUtils.md5Hex("123456"));
                    newAgentaccounts.setMobile(user.getMobile());
                    newAgentaccounts.setCreatetime(new Date());
                    newAgentaccounts.setTid(agentbusiness.getTid());
                    newAgentaccounts.setPid(agentbusiness.getPid());
                    newAgentaccounts.setCid(agentbusiness.getCid());
                    newAgentaccounts.setCityname(agentbusiness.getCityname());
                    newAgentaccounts.setProvince(agentbusiness.getProvince());
                    newAgentaccounts.setCountyname(agentbusiness.getCountyname());
                    waiMaiRunfastAgentaccountsService.insertSelective(newAgentaccounts);
                }else{return Result.fail(null,"找不到对应的代理商！");}
            }
        }else{return Result.fail(null,"传入参数错误！");}
        return Result.ok(null);
    }

    /**
     * 修改用户
     */
    @PostMapping("/update")
    public Result update(@RequestBody BaseUser user){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentaccounts=SessionContext.getCurrentRunfastAgentaccounts();
        if(user!=null && StringUtils.isNotBlank(user.getRealname())&&  StringUtils.isNotBlank(user.getMobile()) && user.getRid()!=null){
            if(admin!=null && admin.getType()==1){
                if(user.getAgentId()!=null){
                    WaiMaiRunfastAgentaccountsExample example=new WaiMaiRunfastAgentaccountsExample();
                    example.createCriteria().andAccountsEqualTo(user.getMobile()).andIdNotEqualTo(user.getId());
                    Integer in=waiMaiRunfastAgentaccountsService.countByExample(example);
                    if(in>0){
                        return Result.fail(null,"该号码已经注册过了！");
                    }
                    WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(user.getAgentId());
                    if(agentbusiness!=null){
                        WaiMaiRunfastAgentaccounts newAgentaccounts=new WaiMaiRunfastAgentaccounts();
                        if(user.getRid()>0){
                            newAgentaccounts.setByroles(user.getRid().toString());
                        }else{return Result.fail(null,"保存人员角色不能为空！");}
                        newAgentaccounts.setId(user.getId());
                        newAgentaccounts.setName(user.getRealname());
                        newAgentaccounts.setMobile(user.getMobile());
                        newAgentaccounts.setAccounts(user.getMobile());
                        //newAgentaccounts.setUpdateTime(new Date());
                        newAgentaccounts.setTid(agentbusiness.getTid());
                        newAgentaccounts.setPid(agentbusiness.getPid());
                        newAgentaccounts.setCid(agentbusiness.getCid());
                        newAgentaccounts.setCityname(agentbusiness.getCityname());
                        newAgentaccounts.setProvince(agentbusiness.getProvince());
                        newAgentaccounts.setCountyname(agentbusiness.getCountyname());
                        waiMaiRunfastAgentaccountsService.updateByPrimaryKeySelective(newAgentaccounts);
                    }else{return Result.fail(null,"找不到对应的代理商！"); }
                }else{
                    BaseUserExample example2=new BaseUserExample();
                    example2.createCriteria().andUsernameEqualTo(user.getMobile()).andIdNotEqualTo(user.getId());
                    Integer in=baseUserService.countByExample(example2);
                    if(in>0){
                        return Result.fail(null,"该号码已经注册过了！");
                    }
                    user.setModifytime(new Date());
                    user.setUsername(user.getMobile());
                    BaseUserRoleExample example=new BaseUserRoleExample();
                    example.createCriteria().andUseridEqualTo(user.getId());
                    List<BaseUserRole> ur=baseUserRoleService.selectByExample(example);
                    if(ur.size()>0){
                        if(ur.get(0).getRid()>0){
                            BaseUserRoleExample example1=new BaseUserRoleExample();
                            example1.createCriteria().andUseridEqualTo(ur.get(0).getUserid());
                            baseUserRoleService.deleteByExample(example1);
                            BaseUserRole ur1=new BaseUserRole();
                            ur1.setRid(user.getRid());
                            ur1.setUserid(user.getId());
                            baseUserRoleService.insertSelective(ur1);
                        }
                    }
                    baseUserService.updateByPrimaryKeySelective(user);
                }
            }else if(admin!=null &&  admin.getType()==2  && agentaccounts!=null){
                WaiMaiRunfastAgentaccountsExample example=new WaiMaiRunfastAgentaccountsExample();
                example.createCriteria().andAccountsEqualTo(user.getMobile()).andIdNotEqualTo(user.getId());
                Integer in=waiMaiRunfastAgentaccountsService.countByExample(example);
                if(in>0){
                    return Result.fail(null,"该号码已经注册过了！");
                }
                WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentaccounts.getAgentid());
                if(agentbusiness!=null){
                    WaiMaiRunfastAgentaccounts newAgentaccounts=new WaiMaiRunfastAgentaccounts();
                    if(user.getRid()>0){
                        newAgentaccounts.setByroles(user.getRid().toString());
                    }else{return Result.fail(null,"保存人员角色不能为空！");}
                    newAgentaccounts.setId(user.getId());
                    newAgentaccounts.setName(user.getRealname());
                    newAgentaccounts.setMobile(user.getMobile());

                    //newAgentaccounts.setUpdateTime(new Date());
                    newAgentaccounts.setTid(agentbusiness.getTid());
                    newAgentaccounts.setPid(agentbusiness.getPid());
                    newAgentaccounts.setCid(agentbusiness.getCid());
                    newAgentaccounts.setCityname(agentbusiness.getCityname());
                    newAgentaccounts.setProvince(agentbusiness.getProvince());
                    newAgentaccounts.setCountyname(agentbusiness.getCountyname());
                    newAgentaccounts.setAccounts(user.getMobile());
                    waiMaiRunfastAgentaccountsService.updateByPrimaryKeySelective(newAgentaccounts);
                }else{return Result.fail(null,"找不到对应的代理商！"); }
            }
        }else{return Result.fail(null,"传入参数错误！");}
        return Result.ok(null);
    }

    /**
     * 删除用户---删除功能暂不支持
     */
    @PostMapping("/delete")
    //@RequiresPermissions("server:user:delete")
    public Result delete(Integer[] userIds){

        Integer id=null;//当前登录用户
        if(ArrayUtils.contains(userIds, 1)){
            return Result.fail(null,"系统管理员不能删除");
        }

        if(ArrayUtils.contains(userIds, id)){
            return Result.fail(null,"当前用户不能删除");
        }

        //sysUserService.deleteBatch(userIds);

        return Result.ok(null);
    }

    /**三种类型登录用户密码修改*/
    @GetMapping("/password")
    public Result   password(String password,String  newPassword){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        if(StringUtils.isNotBlank(password) && StringUtils.isNotBlank(newPassword)){
           if(admin!=null && admin.getType()==1){
              //后台登录
               BaseUser user=baseUserService.selectByPrimaryKey(admin.getId());
               if(user!=null){
                    if(password.equalsIgnoreCase(user.getPassword())){
                        BaseUser user1=new BaseUser();
                        user1.setId(user.getId());
                        user1.setPassword(newPassword);
                        baseUserService.updateByPrimaryKeySelective(user1);
                    }else{return Result.fail(null,"原密码不对！");}
               }else{return Result.fail(null,"找不到对应的用户！");}
           }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){
              //代理商登录
               WaiMaiRunfastAgentbusiness agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentAccounts.getAgentid());
               if(agentbusiness!=null){
                   WaiMaiRunfastAgentaccounts agentaccounts=waiMaiRunfastAgentaccountsService.selectByPrimaryKey(agentAccounts.getId());
                   if(password.equalsIgnoreCase(agentaccounts.getPassword())){
                       WaiMaiRunfastAgentaccounts agentaccounts1=new WaiMaiRunfastAgentaccounts();
                       agentaccounts1.setId(agentAccounts.getId());
                       agentaccounts1.setPassword(newPassword);
                       waiMaiRunfastAgentaccountsService.updateByPrimaryKeySelective(agentaccounts1);
                   }else{return Result.fail(null,"原密码不对！");}
               }else{return Result.fail(null,"找不到对应的代理商！");}
           }else if(admin!=null && admin.getType()==3 && accounts!=null){
              //商家登录
               RunfastBusiness business=runfastBusinessService.selectByPrimaryKey(accounts.getBusinessid());
               if(business!=null){
                   RunfastBusinessAccounts accounts1=runfastBusinessAccountsService.selectByPrimaryKey(accounts.getId());
                   if(password.equalsIgnoreCase(accounts1.getPassword())){
                       RunfastBusinessAccounts accounts2=new RunfastBusinessAccounts();
                       accounts2.setId(accounts.getId());
                       accounts2.setPassword(newPassword);
                       runfastBusinessAccountsService.updateByPrimaryKeySelective(accounts2);
                   }else{return Result.fail(null,"原密码不对！");}
               }else{return Result.fail(null,"找不对应的商家！");}
           }else{return Result.fail(null,"未登录！");}
        }else{return Result.fail(null," 传入参数不对！");}
        return Result.ok(null);
    }


}
